import React from 'react'
import {connect} from 'react-redux';

import App from '../../common/App.jsx'
import Utils from '../../common/U.jsx'
import U from '../../common/U.jsx'
import HtmlEditor from '../common/HtmlEditor.jsx'
import OSSWrap from '../../common/OSSWrap';
import {
    Card,
    Form,
    Input,
    Upload,
    Tooltip,
    Icon,
    Radio,
    Button,
    message, InputNumber
} from 'antd';

import {Link} from 'react-router';
import BreadcrumbCustom from '../BreadcrumbCustom'
import CTYPE from "../../common/CTYPE";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const URL = {
    first: '套餐',
    second: '套餐编辑',
    save: 'adm/pkg/save',
    detail: 'adm/pkg/pkg',
    go: 'app/pkg/packages',
    key: '',
};

class PackageEdit extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            namespace: '',
            id: parseInt(this.props.params.id),
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData = () => {
        let _this = this;
        let id = _this.state.id;
        if (id && id > 0) {
            App.api(URL.detail, {pkgId: id}).then(({title, price, category, intro, img, content}) => {

                _this.props.form.setFieldsValue({title, price, category, intro});
                this.setState({
                    image: img, content
                })
            })
        } else {
            console.log();
        }
    };


    handleSubmit = (e) => {
        let _this = this;
        e.preventDefault();
        _this.props.form.validateFields((err, {title, price, category, intro}) => {
            if (err) {
                Object.keys(err).forEach(key => {
                    message.warning(err[key].errors[0].message);
                });
            }

            App.api(URL.save, {
                title, price, category, intro, img: this.state.image, content: this.state.content,
            }).then(() => {
                message.success('添加成功');
                URL.go && App.go(URL.go);
            })

        });
    };

    handleNewImage = e => {
        if (!e.target.files[0] || e.target.files[0].type.indexOf('image') < 0) {
            message.error('文件类型不正确,请选择图片类型');
            this.setState({
                uploading: false,
            });
            return;
        }

        if (this.state.uploading) {
            message.loading('上传中');
            return;
        }

        this.setState({uploading: true});

        OSSWrap.upload('', e.target.files[0], {
            progress: (p) => {
                this.setState({upload_progress: Math.floor(p * 100)});
            }
        }).then((result) => {
            this.setState({
                upload_progress: 100,
                image: result.url,
                uploading: false,
            });
        }).catch((err) => {
            message.error(err);
        });
    };

    syncContent = (content, index) => {
        let key = 'content';
        this.setState({
            content: content
        })
    };

    render() {
        let _this = this;
        let id = this.props.params.id;
        const {getFieldDecorator} = _this.props.form;
        let content = this.state.content;
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'}/>
                <div className="ant-upload-text">上传</div>
            </div>
        );
        const imageUrl = this.state.imageUrl;
        return (
            <div className="common-edit-page">

                <BreadcrumbCustom first={URL.first} second={URL.second}/>

                <Form onSubmit={this.handleSubmit}>
                    <Card title="编辑图文" bordered={false}
                          extra={<Button type="primary" htmlType="submit">{id > 0 ? '保存' : '发布'}</Button>}
                          style={{minWidth: CTYPE.eidtMinWidth, maxWidth: CTYPE.eidtMaxWidth}}>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>标题</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('title', {})(
                                <Input placeholder={`建议输入字数不超过${CTYPE.maxlength.title}个字`}/>
                            )}
                        </FormItem>


                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>价格</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('price', {
                                rules: [{
                                    type: 'number',
                                    whitespace: true,
                                    min: 0,
                                    max: CTYPE.maxVisitNum,
                                }],
                            })(
                                <InputNumber precision={0}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>分类</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('category')(
                                <RadioGroup>
                                    <Radio value={1}>厨房</Radio>
                                    <Radio value={2}>卫生间</Radio>
                                </RadioGroup>
                            )}
                        </FormItem>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>封面图</span>
                            )}
                            hasFeedback>
                            <p className="uploader">
                                <input className="file"
                                       type='file' onChange={this.handleNewImage}/>
                            </p>
                            {this.state.image && <img src={this.state.image} alt="" style={{width: 100}}/>}
                        </FormItem>

                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>简介</span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('intro', {})(
                                <Input placeholder={`建议输入字数不超过${CTYPE.maxlength.title}个字`}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...CTYPE.formItemLayout}
                            label={(
                                <span>内容详情</span>
                            )}
                        >
                            <HtmlEditor content={content}
                                        syncContent={_this.syncContent}/>
                        </FormItem>


                    </Card>
                </Form>
            </div>
        )

    }
}

const CourseArticleEdit = Form.create()(PackageEdit);

export default CourseArticleEdit;
